//
//  BoundHomeViewController.swift
//  EasePods
//
//  Created by 李然 on 2024/4/3.
//

import UIKit
import RxViewController
import EarbudsFunctions
#if DEBUG
import RealmBrowser
import RxGesture
#endif

class HomeViewController: ViewController {
    
    let viewModel = HomeViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = R.color.common_1_bg_main()
        
        self.navigation.item.leftBarButtonItem = UIBarButtonItem.init(customView: leftButton)
        self.navigation.item.rightBarButtonItem = UIBarButtonItem.init(customView: rightButton)
        self.navigation.item.titleView = titleImageView
    
        
        leftButton.rx.tap
            .subscribe(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                self.showSettingMenu()
            }).disposed(by: rx.disposeBag)
        
        rightButton.rx.tap
            .subscribe(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                let alert = UIAlertController(title: R.string.localizable.device_remove_confirm_title(), message: "", preferredStyle: .alert)
                let okaction = UIAlertAction(title:  R.string.localizable.common_confirm(), style: .default) { (action) in
                    let vc = IgnoreDeviceAlertViewController()
                    self.present(vc, animated: true)
                }
                let cancel = UIAlertAction(title: R.string.localizable.common_cancel(), style: .cancel, handler: nil)
                alert.addAction(okaction)
                alert.addAction(cancel)
                self.present(alert, animated: true, completion: nil)
            }).disposed(by: rx.disposeBag)
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(kNavHeight)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        
        #if DEBUG
        let frame: CGRect = self.view.frame
        let globalButton = RealmGlobalButton(frame: CGRect(x: 100, y: 500, width: 100, height: 100), viewFrame: frame)
        globalButton.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            self.present(RealmBrowser.instantiate(moduleName: "RealmBrowser_Example"), animated: true, completion: nil)
        }).disposed(by: rx.disposeBag)
        self.view.addSubview(globalButton)
        #endif
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        BluetoothManager.shared.receiveCameraAction.subscribe(onNext: {[weak self] state in
            guard let `self` = self else { return }
            
            let topVC = RootViewManager.default.getTopViewController()
            if topVC.isKind(of: CameraViewController.self) {
                guard state == 2 else {
                    return
                }
                RootViewManager.default.rootViewController.dismiss(animated: true)
            }
            
            guard state == 1 else {
                return
            }
            self.settingPush(model: .camera)
        }).disposed(by: rx.disposeBag)
        
        let inPut = HomeViewModel.Input(viewWillAppear: self.rx.viewWillAppear)
        let outPut = viewModel.transform(input: inPut)
        outPut.items.bind(to: tableView.rx.items) { [weak self] tableView, row, item in
            switch item {
            case .headItem(ViewModel: let viewModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: HomeHeadTableViewCell.reuseIdentifier) as! HomeHeadTableViewCell
                cell.bind(viewModel: viewModel)
                cell.useTimeClick = { [weak self] in
                    let vc = UseTimeViewController()
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
                return cell
            case .equalizerItem(viewModel: let viewModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: HomeEqualizerTableViewCell.reuseIdentifier) as! HomeEqualizerTableViewCell
                cell.bind(viewModel: viewModel)
                return cell
            case .spatialAudioSectionItem:
                let cell = tableView.dequeueReusableCell(withIdentifier: HomeSpatialAudioSectionTableViewCell.reuseIdentifier) as! HomeSpatialAudioSectionTableViewCell
                return cell
            case .spatialAudioItem(viewModel: let viewModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: HomeSpatialAudioTableViewCell.reuseIdentifier) as! HomeSpatialAudioTableViewCell
                cell.bind(viewModel: viewModel)
                return cell
            case .settingItem(viewModel: let viewModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: HomeSettingTableViewCell.reuseIdentifier) as! HomeSettingTableViewCell
                cell.bind(viewModel: viewModel)
                cell.didseleBlock = { model in
                    self?.settingPush(model: model)
                }
                return cell
            }
        }.disposed(by: rx.disposeBag)
    }
    
    private func settingPush(model: HomeSettingItem) {
        switch model {
        case .gesture:
            let vc = GestureMenuViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        case .camera:
            
            let nav = NavigationController(rootViewController: CameraViewController())
            nav.modalPresentationStyle = .fullScreen
            RootViewManager.default.rootViewController.present(nav, animated: true)
            
        case .earbuds:
            let vc = EarbudsFindViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    private lazy var leftButton: Button = {
        let button = Button(type: .custom)
        button.setImage(R.image.ic_home_setting(), for: .normal)
        return button
    }()
    
    private lazy var rightButton: Button = {
        let button = Button(type: .custom)
        button.setImage(R.image.ic_home_remove(), for: .normal)
        return button
    }()
    
    private lazy var titleImageView: ImageView = {
        let imageView = ImageView()
        imageView.image = R.image.ic_home_logo()
        return imageView
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(HomeHeadTableViewCell.self, forCellReuseIdentifier: HomeHeadTableViewCell.reuseIdentifier)
        tableView.register(HomeEqualizerTableViewCell.self, forCellReuseIdentifier: HomeEqualizerTableViewCell.reuseIdentifier)
        tableView.register(HomeSpatialAudioSectionTableViewCell.self, forCellReuseIdentifier: HomeSpatialAudioSectionTableViewCell.reuseIdentifier)
        tableView.register(HomeSpatialAudioTableViewCell.self, forCellReuseIdentifier: HomeSpatialAudioTableViewCell.reuseIdentifier)
        tableView.register(HomeSettingTableViewCell.self, forCellReuseIdentifier: HomeSettingTableViewCell.reuseIdentifier)
        tableView.estimatedRowHeight = 60
        tableView.backgroundColor = R.color.common_1_bg_main()
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .none
        return tableView
    }()
}
